﻿using ConfExpert.Datasets;
using ConfExpert.Datasets.MyDataTableAdapters;
using ConfExpert.Forms.Depo;
using ConfExpert.Properties;
using ConfExpert.Utility;

using DevExpress.Utils;
using DevExpress.XtraBars;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;

using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.SatinAlma.YeniYapi
{
    public partial class StokKartiDuzenle : XPopupForm
    {
        int ProductId;
        string ProductIds;
        BindingSource bsProduct, bsUK, bsMK;
        string FocusedColumn;

        public StokKartiDuzenle(string productIds)
        {
            InitializeComponent();
            ProductIds = productIds;
        }

        public StokKartiDuzenle(int _ProductId, string _FocusedColumn)
        {
            InitializeComponent();
            ProductIds = _ProductId.ToString();
            FocusedColumn = _FocusedColumn;
        }

        void StokKartiDuzenle_Load(object sender, EventArgs e)
        {
            TAM.ProductTableAdapter = new ProductTableAdapter();
            TAM.UreticiKodlariTableAdapter = new UreticiKodlariTableAdapter();
            TAM.MusteriKodlariTableAdapter = new MusteriKodlariTableAdapter();

            bsProduct = new BindingSource(ds, "Product");
            bsUK = new BindingSource(bsProduct, "FK_UreticiKodlari_Product_ProductId");
            bsMK = new BindingSource(bsProduct, "FK_MusteriKodlari_Product_ProductId");
            AddBsToList(bsProduct, bsUK, bsMK);

            ds.Product.Columns.Add("CurrentQty", typeof(decimal), "SUM(Child(FK_xStok_Product_ProductId).Qty)");
            ds.Product.TableNewRow += Product_TableNewRow;
            ds.MusteriKodlari.TableNewRow += MusteriKodlari_TableNewRow;

            InitGridView(gvProduct, bsProduct);
            gvProduct.SetCaptions("CurrentQty:Depodaki Metraj");
            gvProduct.MakeColumnsReadOnly("ProductId", "CurrentQty");
            gvProduct.OptionsView.NewItemRowPosition = NewItemRowPosition.None;
            gvProduct.OptionsView.ShowViewCaption = false;
            gvProduct.RowCellStyle += gvProduct_RowCellStyle;
            gvProduct.FocusedRowChanged += gvProduct_FocusedRowChanged;
            gvProduct.Columns["CurrentQty"].VisibleIndex = gvProduct.Columns["Desc7C"].VisibleIndex;
            gvProduct.FormatAsNumber(1, "CurrentQty");
            gvProduct.AddSummary("CurrentQty");
            gvProduct.Columns["Scan"].VisibleIndex = gvProduct.Columns["Name"].VisibleIndex;
            //(gvProduct.Columns["Scan"].ColumnEdit as RepositoryItemPictureEdit).Padding = new System.Windows.Forms.Padding(-1);


            RepositoryItemGridLookUpEdit gleKons = GetIntellisensedRI(RepositoryManager.Kons);
            RepositoryItemGridLookUpEdit gleEn = GetIntellisensedRI(RepositoryManager.En);
            RepositoryItemGridLookUpEdit gleAgr = gleAgr = GetIntellisensedRI(RepositoryManager.Agr);


            gvProduct.Columns["Konstruksiyon"].ColumnEdit = gleKons;
            gvProduct.Columns["EnGrubu"].ColumnEdit = gleEn;
            gvProduct.Columns["Agirlik"].ColumnEdit = gleAgr;

            ((RepositoryItemGridLookUpEdit)gvProduct.Columns["Konstruksiyon"].ColumnEdit).ProcessNewValue += ri_ProcessNewValue2;
            ((RepositoryItemGridLookUpEdit)gvProduct.Columns["EnGrubu"].ColumnEdit).ProcessNewValue += ri_ProcessNewValue2;
            ((RepositoryItemGridLookUpEdit)gvProduct.Columns["Agirlik"].ColumnEdit).ProcessNewValue += ri_ProcessNewValue2;
            //((RepositoryItemGridLookUpEdit)gvProduct.Columns["KaliteId"].ColumnEdit).Closed += KaliteId_Changed;

            gvProduct.CellValueChanged += gvProduct_CellValueChanged;

            gvProduct.RowStyle += gvProduct_RowStyle;
            /*
            UserId	Name
            4	    Cemal
            7	    Esti
            85	    Şadiye
            */
            bool yetkili = ytk(69);

            //yetkili = yetkili || isDeveloper;

            if (!yetkili)
            {
                gvProduct.MakeReadOnly();
                btnKaydet.Visibility = BarItemVisibility.Never;
            }

            GridManager gm = GridManager.GetManager(gvProduct);
            //gm.GridMenu.AddMenu("Teknik özellikleri güncelle", Teknik);
            gm.GridMenu.AddMenu("Bu artikelin hareketleri", HareketleriGoster);
            gm.GridMenu.AddMenu("Bu artikelin benzerleri", FindSimilar, Resources.CustomerReports_Icon);

            InitGridView(gvUK, bsUK);
            gvUK.MakeColumnInvisible("UreticiKodlariId", "Scan", "PRO");
            gvUK.OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom;
            gvUK.RowCellStyle += gvUK_RowCellStyle;
            gvUK.Columns["KaliteAciklama"].VisibleIndex = gvUK.Columns["UreticiKodu"].VisibleIndex + 1;

            InitGridView(gvMK, bsMK);
            gvMK.MakeColumnInvisible("MusteriKodlariId", "Scan", "ProductId");
            gvMK.OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom;
            gvMK.RowCellStyle += gvMK_RowCellStyle;
            //gvMK.DoubleClick += gvMK_DoubleClick;

            btnKaydet.ItemClick += btnKaydet_ItemClick;
            btnKodlar.CheckedChanged += btnKodlar_CheckedChanged;

            RefreshData();

            splitter.AcKapa(false);

            gvProduct.BestFitColumns();

            ds.UreticiKodlari.TableNewRow += UreticiKodlari_TableNewRow;
            gvMK.Columns["UserId"].OptionsColumn.AllowEdit = false;
            gvUK.Columns["UserId"].OptionsColumn.AllowEdit = false;

            if (ProductId > 0)
            {
                gvProduct.FocusedRowHandle = 0;
                gvProduct.FocusedColumn = gvProduct.Columns[FocusedColumn];
                gvProduct.ShowEditor();
            }
        }

        void gvProduct_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName == "KaliteId")
            {
                gvProduct.EndEditing();
                KaliteChanged(gvProduct.FocusedRowHandle);
            }
        }

        void UreticiKodlari_TableNewRow(object sender, System.Data.DataTableNewRowEventArgs e)
        {
            e.Row["UserId"] = WhoAmI;
        }

        void btnKaydet_ItemClick(object sender, ItemClickEventArgs e)
        {
            gvProduct.SelectAll();
            Teknik(null, null);

            Save();
            RefreshLookups();
            AppSession.MainForm.NotifyMain("Kaydedildi.");
            this.DialogResult = DialogResult.OK;
        }

        void FindSimilar(object sender, EventArgs e)
        {
            int productID = bsProduct.GetCurrentValue("ProductId").ToInt(-1);
            FindSimilarBenzerRenk(productID);
        }

        void RefreshData()
        {
            GetDetails("Product;UreticiKodlari;MusteriKodlari;xStok", "GetStokSel", ProductIds);
        }

        void Teknik(object sender, EventArgs e)
        {
            gvProduct.EndEditing();
            foreach (int rowHandle in gvProduct.GetSelectedRows())
                if (rowHandle > -1)
                    KaliteChanged(rowHandle);
        }

        void HareketleriGoster(object sender, EventArgs e)
        {
            int productId = bsProduct.GetCurrentValue("ProductId").ToInt(-1);
            if (productId > 0)
                using (DepoStokHareketler rzv = new DepoStokHareketler(productId))
                    rzv.ShowDialog();
        }

        void gvMK_DoubleClick(object sender, EventArgs e)
        {
            using (Araclar.Brand2Customer b = new Araclar.Brand2Customer())
            {
                if (b.ShowDialog() == DialogResult.OK)
                {
                    if (gvMK.FocusedRowHandle != DevExpress.XtraGrid.GridControl.NewItemRowHandle)
                        gvMK.SetFocusedRowCellValue("CustomerId", b.CustomerId);
                    else
                    {
                        MyData.MusteriKodlariRow mkr = ds.MusteriKodlari.NewMusteriKodlariRow();
                        mkr.ProductId = ProductId;
                        mkr.CustomerId = b.CustomerId;
                        ds.MusteriKodlari.AddMusteriKodlariRow(mkr);
                    }

                    gvMK.BestFitColumns();
                }
            }
        }

        void KaliteChanged(int rh)
        {
            if (rh > -1)
            {
                DataRow r = gvProduct.GetDataRow(rh);
                int KaliteId = r["KaliteId"].ToInt();

                if (KaliteId > 0)
                {
                    AppSession.Lookups.V_Kumas.FindByProductId(r["ProductId"].ToInt()).KaliteId = KaliteId;

                    gvProduct.SetRowCellValue(rh, "KaliteAciklama", null);

                    MyData.KaliteRow kr = AppSession.Lookups.Kalite.FindByKaliteId(KaliteId);

                    if (!kr.IsVendorIdNull())
                    {
                        if (kr.VendorId != 33) //KARBEL DEPO
                            gvProduct.SetRowCellValue(rh, "KVendorId", kr.VendorId);
                    }
                    else
                        gvProduct.SetRowCellValue(rh, "KVendorId", null);

                    if (!kr.IsFinishIdNull())
                        gvProduct.SetRowCellValue(rh, "FinishId", kr.FinishId);
                    //else
                    //    SetVal("FinishId", null);

                    if (!kr.IsKompozisyonIdNull())
                        gvProduct.SetRowCellValue(rh, "KompozisyonId", kr.KompozisyonId);
                    else
                        gvProduct.SetRowCellValue(rh, "KompozisyonId", null);

                    if (!kr.IsKonstruksiyonNull())
                        gvProduct.SetRowCellValue(rh, "Konstruksiyon", kr.Konstruksiyon);
                    else
                        gvProduct.SetRowCellValue(rh, "Konstruksiyon", null);

                    if (!kr.IsEnGrubuNull())
                        gvProduct.SetRowCellValue(rh, "EnGrubu", kr.EnGrubu);
                    //else
                    //    SetVal("EnGrubu", null);

                    if (!kr.IsAgirlikNull())
                        gvProduct.SetRowCellValue(rh, "Agirlik", kr.Agirlik);
                    //else
                    //    SetVal("Agirlik", null);

                    if (!kr.IsGrupESPIdNull())
                        gvProduct.SetRowCellValue(rh, "GrupESPId", kr.GrupESPId);
                    //else
                    //    SetVal("GrupESPId", null);

                    if (!kr.IsFabricTypeIdNull())
                        gvProduct.SetRowCellValue(rh, "FabricTypeId", kr.FabricTypeId);
                    else
                        gvProduct.SetRowCellValue(rh, "FabricTypeId", null);
                }
                else
                    AppSession.Lookups.V_Kumas.FindByProductId(r["ProductId"].ToInt()).SetKaliteIdNull();

            }
        }

        void gvProduct_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle > -1)
            {
                ProductId = bsProduct.GetCurrentValue("ProductId").ToInt(-1);
                if (ds.Product.FindByProductId(ProductId) != null)
                    lblHeader.Caption = ds.Product.FindByProductId(ProductId).Name;
                else
                    lblHeader.Caption = string.Empty;
            }
        }

        void Product_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["UserId"] = WhoAmI;
        }

        void MusteriKodlari_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["UserId"] = WhoAmI;
        }

        void btnKodlar_CheckedChanged(object sender, ItemClickEventArgs e)
        {
            splitter.AcKapa(btnKodlar.Checked);
        }

        void gvUK_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.RowHandle > -1)
            {
                if (e.Column.FieldName.Contains("VendorId"))
                    e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);

                if (gvUK.GetRowCellValue(e.RowHandle, "isOriginal") != null)
                    if (gvUK.GetRowCellValue(e.RowHandle, "isOriginal") != DBNull.Value)
                        if ((bool)gvUK.GetRowCellValue(e.RowHandle, "isOriginal"))
                            e.Appearance.BackColor = System.Drawing.Color.LightBlue;
            }
        }

        void gvMK_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.RowHandle >= 0)
                if (e.Column.FieldName.Contains("BrandId"))
                    e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
        }

        void gvProduct_RowStyle(object sender, RowStyleEventArgs e)
        {
            GridView gv = sender as GridView;
            if (e.RowHandle >= 0)
                if (gv.GetRowCellValue(e.RowHandle, "Deleted") != null)
                    if (gv.GetRowCellValue(e.RowHandle, "Deleted") != DBNull.Value)
                        if ((bool)gv.GetRowCellValue(e.RowHandle, "Deleted"))
                        {
                            e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Strikeout);
                            e.Appearance.ForeColor = Color.Gray;
                        }
        }

        void gvProduct_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.RowHandle > -1)
            {
                GridView view = sender as GridView;
                if (intParse(view.GetRowCellValue(e.RowHandle, "ProductId")) == ProductId && ProductId > 0)
                    e.Appearance.BackColor = System.Drawing.Color.YellowGreen;
                else
                    e.Appearance.Combine((e.RowHandle & 1) != 0 ? view.Appearance.EvenRow : view.Appearance.OddRow);

                switch (e.Column.FieldName)
                {
                    case "Name":
                        e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
                        break;
                }
            }
        }
    }
}